package middleware

import (
	"encoding/json"
	log "github.com/sirupsen/logrus"

	"strconv"
	"web_framework/config"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/storage"
)

func GetDeviceUserBind(uid int) ([]model.Router, error) {

	log.Info("Uid"+strconv.Itoa(uid))

	var bind []model.Router
	bindKey := constvar.RedisDeviceBind + strconv.Itoa(uid)
	find, err := storage.RedisGetList(bindKey)
	if err != nil {
		return bind, err
	}

	if len(find) < 1 {
		// 去数据库取值
		bind, err = storage.GetDeviceUserBindByUid(config.C.DB.DB, uid)
		if err != nil {
			return bind, err
		}
		// 放入redis
		bo, err := storage.RedisSet(bindKey, bind, constvar.RedisExpireMinute30)
		if bo {
			return bind, nil
		}
		return bind, err
	}

	errShal := json.Unmarshal(find, &bind)
	if errShal != nil {
		return bind, errShal
	}

	return bind, nil
}
